from fastapi import APIRouter, Query,BackgroundTasks
from tortoise.expressions import Q,F
from app.controllers.appointment.list import appointment_list_controller
from app.controllers.orders.list import orders_list_controller
from app.controllers.system.user import user_controller
from app.core.ctx import CTX_USER_ID
from app.core.dependency import DependCustomerAuth
from app.models import CustomerUser
from app.schemas.appointment import AppointmentListUpdate, AppointmentListCreate, AppointmentListNewCreate
from app.schemas.base import Success, SuccessExtra,Fail
from app.schemas.orders import OrdersListCreateMini
from app.settings import settings
from app.controllers.appointment.space import appointment_space_controller
from app.models.appointment import AppointmentList, AppointmentSalon, AppointmentProject, AppointmentDesigner
from app.utils.excel import create_excel,date_format
from fastapi.responses import JSONResponse

appointment_list_router = APIRouter()
model_name = "预约"


@appointment_list_router.get("/list", summary=f"查看{model_name}列表", dependencies=[DependCustomerAuth])
async def do_list(
        page: int = Query(1, description="页码"),
        page_size: int = Query(10, description="每页数量"),
        type: int  = Query(None, description="大类"),
        d_type: int  = Query(None, description="小类"),
        space_id: int  = Query(None, description="门店id"),
        start_time: str = Query("", description="开始时间"),
        end_time: str = Query("", description="结束时间"),
        customer_id=Query(0, description="用户id"),
):
    q = Q()
    user_id = CTX_USER_ID.get()
    user = await user_controller.get(user_id)
    if user.space_id:
        q &= Q(space_id__in=user.space_id)
    if customer_id:
        user_id = customer_id
        q &= Q(user_id=user_id)
    if type:
        q &= Q(type=type)
    if d_type:
        q &= Q(type=d_type)
    if space_id:
        q &= Q(space_id=space_id)
    if start_time and end_time:
        q &= Q(time__range=[start_time, end_time])
    elif start_time:
        q &= Q(time__gte=start_time)
    elif end_time:
        q &= Q(time__lte=end_time)
    total, data = await appointment_list_controller.do_list(page=page, page_size=page_size, search=q)
    space_objs = await appointment_space_controller.level_list()

    for item in data:
        item['type_name'] = settings.APPOINTMENT_T[item['type']]
        if item['d_type']>0:
            item['d_type_name'] = settings.APPOINTMENT_TYPE[item['d_type']]
        else:
            item['d_type_name'] = "无"
        if item['space_id']>0:
            item['space_name'] = space_objs[item['space_id']]
        else:
            item['space_name'] = "无"
        item['status_name'] = settings.APPOINTMENT_STATUS[item['status']]
        if item['designer_names']:
            item['designer_name_s'] = ", ".join(item['designer_names'])
        else:
            item['designer_name_s'] = ""
        if item['ex_project_names']:
            item['ex_names'] = ", ".join(item['ex_project_names'])
            item['project_name_s'] = f"{item['project_name']}({item['ex_names']})"
        else:
            item['ex_names']=""
    return SuccessExtra(data=data, total=total, page=page, page_size=page_size)

@appointment_list_router.get("/get", summary=f"查看{model_name}")
async def do_get(
        data_id: int = Query(..., description="ID"),
):
    data = await appointment_list_controller.do_detail(data_id=data_id)
    return Success(data=data)

@appointment_list_router.post("/create", summary="提交预约表单", dependencies=[DependCustomerAuth])
async def do_save(
        data_in: AppointmentListNewCreate,
):
    user_id = CTX_USER_ID.get()
    if data_in.user_id:
        user_id = data_in.user_id
    appointment = await AppointmentList.filter(user_id=user_id).filter(time=data_in.time).first()
    if appointment:
        return JSONResponse(content={"code": 400, "msg": "已经预约成功啦"}, status_code=200)
    if data_in.type == 3:
        salon = await AppointmentSalon.filter(id=data_in.project_id).first().values("number", "number_have")
        number = salon['number']
        number_have = salon['number_have']
        if number_have >= number:
            return JSONResponse(content={"code": 400, "msg": "报名人数已满"}, status_code=200)

    ##保存提交表单
    user = await CustomerUser.filter(id=user_id).first().values("name", "card_no", "role_id", "phone")
    data_in.user_id = user_id
    data_in.user_name = user['name']
    data_in.user_card_no = user['card_no']
    data_in.user_type = user['role_id']
    data_in.user_phone = user['phone']
    data_in.status = 1

    for item in data_in.projects:
        project_id = item['project_id']
        designer_id = item['designer_id']
        if designer_id:
            designer_data = await AppointmentDesigner.filter(id=designer_id).values("name")
            data_in.designer_names = [item["name"] for item in designer_data]
        project = await AppointmentProject.filter(id=project_id).first().values("name","interval")
        data_in.project_name = project["name"]
        data_in.longs = project['interval']
        data_in2 = AppointmentListCreate(
            user_id=data_in.user_id,
            user_name=data_in.user_name,
            user_card_no=data_in.user_card_no,
            user_type=data_in.user_type,
            user_phone=data_in.user_phone,
            status=data_in.status,
            type=data_in.type,
            project_id=project_id,
            project_name=data_in.project_name,
            designer_ids=[designer_id],
            designer_names=data_in.designer_names,
            time=data_in.time,
            longs=data_in.longs,
            space_id=data_in.space_id,
            come_nums=1,
        )
        await appointment_list_controller.do_create(obj_in=data_in2)

    return Success(msg="提交成功")

@appointment_list_router.post("/update", summary=f"更新{model_name}")
async def do_update(
        data_in: AppointmentListUpdate,
):
    ##查到原来不是驳回状态的,如果改了沙龙驳回,沙龙字段number_have要减少1
    appointment = await AppointmentList.filter(id=data_in.id).first().values("status")
    num = appointment['status']
    if num != 2 and data_in.status ==2 and data_in.type==3:
        await AppointmentSalon.filter(id=data_in.project_id).update(number_have=F('number_have') - 1)
    if num == 2 and data_in.status ==1 and data_in.type==3:
        await AppointmentSalon.filter(id=data_in.project_id).update(number_have=F('number_have') + 1)
    await appointment_list_controller.do_update(obj_in=data_in)
    return Success(msg="更新成功")

@appointment_list_router.delete("/delete", summary=f"删除{model_name}")
async def do_delete(
        data_id: int = Query(..., description="ID"),
):
    await appointment_list_controller.do_delete(data_id=data_id)
    return Success(msg="删除成功")

@appointment_list_router.get("/type", summary="获取预约大类")
async def list_type():
    level_objs = settings.APPOINTMENT_T
    data = []
    key = 0
    for level in level_objs:
        if level:
            data.append({"label":level,"value":key})
        key += 1
    return Success(data=data)

@appointment_list_router.get("/excel", summary="导出数据")
async def list_excel(
        back_tasks: BackgroundTasks,
        start_time: str = Query("", description="开始时间"),
        end_time: str = Query("", description="结束时间"),
):
    q = Q()
    if start_time and end_time:
        q &= Q(created_at__range=[start_time, end_time])
    elif start_time:
        q &= Q(created_at__gte=start_time)
    elif end_time:
        q &= Q(created_at__lte=end_time)
    space_objs = await appointment_space_controller.level_list()
    name = f"预约数据{start_time}~{end_time}"
    data = await AppointmentList.filter(q).all().select_related("parent").values(
        预约大类='type',
        预约子类='d_type',
        预约时间='time',
        门店="space_id",
        设计师="designer_name",
        项目名称="project_name",
        用户="user_name",
        用户卡号="user_card_no",
        审核状态="status",
    )

    for item in data:
        item["预约时间"] = date_format(item["预约时间"])
        item['预约大类'] = settings.APPOINTMENT_T[item['预约大类']]
        item['预约子类'] = settings.APPOINTMENT_TYPE[item['预约子类']]
        if item['门店']>0:
            item['门店'] = space_objs[item['门店']]
        item['审核状态'] = settings.APPOINTMENT_STATUS[item['审核状态']]

    back_tasks.add_task(create_excel, name=name,data=data)
    return JSONResponse(content={"code": 200, "message": "开始生成excel,请去下载中心查看"}, status_code=200)




